function getUrlParam(name)
{
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r!=null) return unescape(r[2]); return null; //返回参数值
}

$(function () {
    var begin = 0;
    var limit = 20;
    var fetching = false;
    var hasMore = true;
    var topicId = parseInt(getUrlParam('topicid'));
    var topicInfoTemplate = _.template($("#topic-info-template").html());
    var noteTemplate = _.template($("#note-template").html());
    var winH = $(window).height(); //页面可视区域高度
    var winW = $(window).width();
    var topicObj;

    function checkAuth() {
        if(!window.auth) {
            window.location.href="/web/signin";
            return false;
        } else {
            return true;
        }
    }

    function refreshProgress($container) {
        var imgCount = $container.find(".nt-simgs img").length;
        var progress = 0;
        var note = $container.find(".nt-content").text().trim();
        var tags = $container.find(".tn-tag");
        var places = $container.find(".tn-place");

        if(imgCount === 1) {
            progress += 50;
        } else if(imgCount >= 2) {
            progress += 70;
        }

        if(note) {
            progress += 10;
        }

        if(tags.length) {
            progress += 10;
        }

        if(places.length) {
            progress += 10;
        }

        $container.find(".nt-comp-l").css("width", progress + "%");
        $container.find(".nt-comp-num").text(progress + "%");
    }

    function afterTopicInfoLoad() {
        $(".tn-post-btn").on("click", function() {
            if(!checkAuth()) {
                return;
            }

            window.location.href = "/web/note/post?topicid=" + topicId;
        });

        $("#do-like").on("click", function(e) {
            var $current = $(this);

            if(!checkAuth()) {
                return;
            }

            var topicLikePostUrl = "/api/topic/like/post";
            var topicLikeDelUrl = "/api/topic/like/del";
            var url, likeType;
            if($current.find(".icon-star-empty").length) {
                url = topicLikePostUrl;
                likeType = 'add';
            } else {
                url = topicLikeDelUrl;
                likeType = 'del';
            }

            var data = {
                postData: JSON.stringify({
                    idx: 0,
                    params: {
                        topicid: topicId
                    }
                })
            };

            $.ajax({
                beforeSend: function() {
                    $current.addClass("disabled");
                },
                url: url,
                data: data,
                type: "post",
                dataType: "json",
                success: function(res) {
                    if(res.ret == 0) {
                        if(likeType == 'add') {
                            $current.find(".icon").removeClass("icon-star-empty")
                                .addClass("icon-star");
                        } else {
                            $current.find(".icon").removeClass("icon-star")
                                .addClass("icon-star-empty");
                        }
                    } else {
                        alert(res.msg);
                    }
                },
                complete: function() {
                    $current.removeClass("disabled");
                }
            })
        });
    }

    function initTopicInfo() {
        var topicInfoUrl = '/api/topic/one';

        var data = {
            postData: JSON.stringify({
                idx: 0,
                params: {
                    topicid: topicId
                }
            })
        };

        $.ajax({
            url: topicInfoUrl,
            data: data,
            type: 'post',
            dataType: 'json',
            success: function (res) {
                if (res.ret == 0) {
                    $(".tn-container").append(topicInfoTemplate(res.res));
                    topicObj = res.res;
                    afterTopicInfoLoad();
                    weixinCallback();
                } else {
                    console.log(res)
                }
            },
            error: function (res) {
                console.log(res)
            }
        });
    }

    function afterNoteLoad($container) {
        refreshProgress($container);

        $container.find(".nt-like").on("click", function(e) {
            if(!checkAuth()) {
                return;
            }

            var $current = $(e.currentTarget);

            var noteId = $current.closest(".note").attr("data-note-id");

            var noteLikePostUrl = "/api/note/like/post";
            var noteLikeDelUrl = "/api/note/like/del";
            var url, likeType;
            if($current.find(".icon-hot-empty").length) {
                url = noteLikePostUrl;
                likeType = 'add';
            } else {
                url = noteLikeDelUrl;
                likeType = 'del';
            }

            var data = {
                postData: JSON.stringify({
                    idx: 0,
                    params: {
                        noteid: noteId
                    }
                })
            };

            $.ajax({
                url: url,
                data: data,
                type: "post",
                dataType: "json",
                beforeSend: function() {
                    $current.addClass("disabled");
                },
                success: function(res) {
                    if(res.ret == 0) {
                        var $count = $current.find(".like-count");
                        var count = parseInt($count.text());
                        if(likeType == 'add') {
                            $current.find(".icon").removeClass("icon-hot-empty")
                                .addClass("icon-hot");
                            $count.text(count + 1);
                        } else {
                            $current.find(".icon").removeClass("icon-hot")
                                .addClass("icon-hot-empty");
                            $count.text(count - 1);
                        }
                    } else {
                        alert(res.msg);
                    }
                },
                complete: function() {
                    $current.removeClass("disabled");
                }
            })
        });

        $container.find(".nt-limg").on("click", function(e) {
            e.preventDefault();

            var $current = $(e.currentTarget);
            var $imgs = $current.children();

            var fancyImgs = "";
            $imgs.each(function() {
                var isrc = $(this).attr("src");
                fancyImgs += '<div class="swiper-slide">' +
                    '<div class="fancy-box-in" style="height:' + winH + 'px;width:'
                    + winW + 'px">' +
                    '<img src="' +
                    isrc +
                    '">' +
                    '</div>' +
                    '</div>'
            });

            var fancyBoxTemplate = _.template('<div class="fancy-box-out">' +
                '<div class="swiper-container">' +
                '<div class="swiper-wrapper">' +
                fancyImgs +
                '</div>' +
                '<div class="swiper-pagination"></div>' +
                '</div>' +
                '</div>');
            $("body").append(fancyBoxTemplate());

            var indexSlide = $current.find(".active").index();

            initSlider(indexSlide);
        });
    }

    function renderNoteList() {
        if (fetching) {
            return;
        }
        fetching = true;

        var noteListUrl = "/api/note/list";
        var data = {
            postData: JSON.stringify({
                idx: 0,
                params: {
                    topicid: topicId,
                    begin: begin,
                    limit: limit
                }
            })
        };

        $.ajax({
            url: noteListUrl,
            data: data,
            type: "post",
            dataType: "json",
            success: function (res) {
                if (res.ret == 0) {
                    $.each(res.res, function (index, noteInfo) {
                        $(".note-l-c").append(noteTemplate(noteInfo));
                        afterNoteLoad($(".note[data-note-id=" + noteInfo.noteid + "]"));
                    });
                    begin += limit;
                    if(res.res.length < limit) {
                        hasMore = false;
                    }
                } else {
                    console.log(res);
                }
            },
            error: function (res) {
                console.log(res);
            },
            complete: function() {
                fetching = false;
            }
        });
    }

    $("body").on("click", ".nt-simgs img", function(e) {
        e.preventDefault();
        e.stopPropagation();

        var $current = $(e.currentTarget);
        var index = $current.index();

        $current.siblings().removeClass("active");
        $current.addClass("active");

        var imgelem = $current.closest(".nt-imgs").find(".nt-limg .img");
        var imgelemshow = imgelem.eq(index);
        imgelem.removeClass("active");
        imgelemshow.addClass("active");
    });

    function initSlider(initSlide) {
        var swiper = new Swiper('.swiper-container', {
            pagination: '.swiper-pagination',
            paginationClickable: false,
            loop: false,
            initialSlide: 0 || initSlide
        });
    }

    $("body").on("click", ".fancy-box-out", function(e) {
        var $current = $(e.currentTarget);

        $current.remove();
    });



    $(window).scroll(function () {
        if(!hasMore) {
            return;
        }

        var pageH = $(document.body).height();
        var scrollT = $(window).scrollTop(); //滚动条top
        var aa = (pageH-winH-scrollT)/winH;
        if(aa < 0.02){
            renderNoteList();
        }
    });

    initTopicInfo();
    renderNoteList();

    /* --------- weixin ---------- */
    wx.config(window.wxConfig);

    function weixinCallback() {
        wx.ready(function () {
            wx.onMenuShareAppMessage({
                title: topicObj.title,
                desc: topicObj.summary,
                link: window.location.href,
                imgUrl: topicObj.imglink,
                trigger: function (res) {
                },
                success: function (res) {
                },
                cancel: function (res) {
                },
                fail: function (res) {
                }
            });

            wx.onMenuShareTimeline({
                title: topicObj.title,
                link: window.location.href,
                imgUrl: topicObj.imglink,
                trigger: function (res) {
                    // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回
                },
                success: function (res) {
                },
                cancel: function (res) {
                },
                fail: function (res) {
                }
            });
        });

        wx.error(function (res) {
            alert(res.errMsg);
        });
    }
    /* --------------------------- */
});